﻿using DeHeng_Mes.Constant;
using DeHeng_Mes.Model.Table;
using DeHeng_Mes.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
using System.Diagnostics;

namespace DeHeng_Mes.Dao
{
    public class ErrorStatusDao
    {
        /// <summary>
        /// 删除符合条件的数据
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="code"></param>
        public void Delete(string methodName, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<TraceNotSave>()
                  .Where(x => x.MethodName == methodName && x.TraceId == code)
                  .ExecuteCommand();
                db.Deleteable<OrderTrace>()
                 .Where(x => x.TraceId == code || x.FictitiousCode == code)
                 .ExecuteCommand();

            }
        }

        /// <summary>
        /// 插入没有创建的数据
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="code"></param>
        public void InsertIsNotCreate(string methodName, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var data = new TraceNotSave
                {
                    MethodName = methodName,
                    TraceId = code,
                    Status = SystemConstant.dataNotCreate, // 假设用Status来标识不同状态
                    CreateTime = DateTime.Now
                };

                db.Insertable(data).ExecuteCommand();
            }
        }

        /// <summary>
        /// 插入保存失败的数据
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="code"></param>
        /// <param name="process"></param>
        public void InsertSaveFailed(string methodName, string code, string process = "")
        {
            using (var db = SqlSugarConfig.Db)
            {
                try
                {
                    db.Ado.BeginTran();
                    // 定义一条数据
                    var data = new TraceNotSave
                    {
                        MethodName = methodName,
                        TraceId = code,
                        process = process,
                        AttemptCount = 1,
                        Status = SystemConstant.InsertDataIllegal,
                        CreateTime = DateTime.Now
                    };

                    // 查询是否存在与 `MethodName`, `TraceId`, `Status` 相同的数据
                    var existingData = db.Queryable<TraceNotSave>()
                        .Where(x => x.MethodName == data.MethodName &&
                                    x.TraceId == data.TraceId &&
                                    x.process == data.process &&
                                    x.Status == data.Status)
                        .First();

                    if (existingData != null)
                    {
                        // 如果存在相同数据，则更新 `CreateTime`,并且将尝试次数加1
                        db.Updateable<TraceNotSave>()
                            .SetColumns(x => x.CreateTime == DateTime.Now)
                            .SetColumns(y => y.AttemptCount == y.AttemptCount + 1)
                            .Where(x => x.id == existingData.id) // 假设有主键 Id
                            .ExecuteCommand();
                    }
                    else
                    {
                        // 如果不存在相同数据，则插入新数据
                        db.Insertable(data).ExecuteCommand();
                    }
                    db.Ado.CommitTran();
                }
                catch (Exception)
                {
                    db.Ado.RollbackTran();
                    throw;
                }
            }

        }

        public void DeleteSaveFailed(string methodName, string code, string process = "")
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 定义一条数据
                var data = new TraceNotSave
                {
                    MethodName = methodName,
                    TraceId = code,
                    process = process,
                    AttemptCount = 1,
                    Status = SystemConstant.InsertDataIllegal,
                    CreateTime = DateTime.Now
                };

                // 查询是否存在与 `MethodName`, `TraceId`, `Status` 相同的数据
                var existingData = db.Queryable<TraceNotSave>()
                    .Where(x => x.MethodName == data.MethodName &&
                                x.TraceId == data.TraceId &&
                                x.process == data.process &&
                                x.Status == data.Status)
                    .First();

                if (existingData != null)
                {
                    // 如果存在相同数据，则删除插入失败记录
                    db.Deleteable<TraceNotSave>()
                        .Where(x => x.id == existingData.id) // 假设有主键 Id
                        .ExecuteCommand();
                }
                else
                {
                    //如果不存在插入失败操作，则无操作
                    return;
                }
            }

        }

        /// <summary>
        /// 插入保存进分表失败的数据，若插入失败则更新创建时间
        /// </summary>
        /// <param name="methodName"></param>
        /// <param name="code"></param>
        public void InsertSectionFailed(string methodName, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                try
                {
                    db.Ado.BeginTran();
                    // 定义一条数据
                    var data = new TraceNotSave
                    {
                        MethodName = methodName,
                        TraceId = code,
                        AttemptCount = 1,
                        Status = SystemConstant.InsertTableIllegal,
                        CreateTime = DateTime.Now
                    };

                    // 查询是否存在与 `MethodName`, `TraceId`, `Status` 相同的数据
                    var existingData = db.Queryable<TraceNotSave>()
                        .Where(x => x.MethodName == data.MethodName &&
                                    x.TraceId == data.TraceId &&
                                    x.Status == data.Status)
                        .First();

                    var insertDataIllegal = db.Queryable<TraceNotSave>()
                   .Where(x => x.Status == SystemConstant.InsertDataIllegal &&
                               x.MethodName == methodName)
                   .First();
                    if (insertDataIllegal != null)
                    {
                        db.Ado.CommitTran();
                        return;
                    }
                    else
                    {
                        if (existingData != null)
                        {
                            // 如果存在相同数据，则更新 `CreateTime`,并且将失败尝试次数加1
                            db.Updateable<TraceNotSave>()
                                .SetColumns(x => x.CreateTime == DateTime.Now)
                                .SetColumns(y => y.AttemptCount == y.AttemptCount + 1)
                                .Where(x => x.id == existingData.id) // 假设有主键 Id
                                .ExecuteCommand();
                        }
                        else
                        {
                            // 如果不存在相同数据，则插入新数据
                            db.Insertable(data).ExecuteCommand();
                        }
                    }
                    db.Ado.CommitTran();
                }
                catch (Exception)
                {
                    db.Ado.RollbackTran();
                    throw;
                }
            }
        }

        /// <summary>
        /// 查询所有符合条件的数据返回一个列表
        /// </summary>
        /// <param name="code"></param>
        public List<TraceNotSave> SelectByCode(string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceNotSave>()
                    .Where(x => x.TraceId == code)
                    .ToList();
            }
        }

        /// <summary>
        /// 根据二维码、方法名、状态值查询数据是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool IsNotCreate(string name, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceNotSave>()
                    .Where(x => x.TraceId == code && x.MethodName == name && x.Status == SystemConstant.nCreate)
                    .Any();
            }
        }

        /*/// <summary>
        /// 根据二维码、方法名、状态值查询数据是否存在
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public bool HasFailed(string name, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                return db.Queryable<TraceNotSave>()
                    .Where(x => x.TraceId == code && x.MethodName == name && x.Status == SystemConstant.insertIllegal)
                    .Any();
            }
        }*/

        /// <summary>
        /// 根据二维码与方法名更新状态为保存失败
        /// </summary>
        /// <param name="name"></param>
        /// <param name="code"></param>
        public void UpdateSaveFailed(string name, string code)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<TraceNotSave>()
                  .SetColumns(x => x.Status == SystemConstant.illegal)
                  .Where(x => x.TraceId == code && x.MethodName == name)
                  .ExecuteCommand();
            }
        }
        public void UpdateNotSaveCreateTime(string name, string code, DateTime dateTime)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Updateable<TraceNotSave>()
                    .SetColumns(x => x.CreateTime == dateTime)
                    .Where(x => x.Status == SystemConstant.nCreate && x.TraceId == code && x.MethodName == name)
                    .ExecuteCommand();
            }
        }

        public void DeleteTraceNotSaveByTraceId(string traceId)
        {
            using (var db = SqlSugarConfig.Db)
            {
                db.Deleteable<TraceNotSave>()
                    .Where(x => x.TraceId == traceId)
                    .ExecuteCommand();
            }
        }

        public void DeleteTraceNotSavePrecise(string traceId, string methodName, string status)
        {
            using (var db = SqlSugarConfig.Db)
            {
                var r = db.Deleteable<TraceNotSave>()
                       .Where(x => x.TraceId == traceId && x.MethodName == methodName && x.Status == status)
                       .ExecuteCommand();
                string va = r.ToSqlValue();
            }
        }

        public List<TraceNotSave> SelectTraceNotSaves()
        {
            using (var db = SqlSugarConfig.Db)
            {
                // 查询 TraceNotSave 表中的所有数据并转换为 List
                return db.Queryable<TraceNotSave>().ToList();
            }
        }
    }
}
